﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using IMLibrary.Controls;
using IMLibrary.Controls.ExControls;
using Ourmsg.FileTransmit;
using Ourmsg.Enum;
using IMLibrary.Security;
using OurMsg.Controls;
using P;

namespace OurMsg
{
    public partial class FormTalkUser  :FormEx // Win8Form
    {
        public FormTalkUser()
        {
            InitializeComponent(); 
            ToolStrip1.FormBackColor = this.BackColor;

            panelMessage1.CreateMsgAfter += (s, e) => OnCreateMsgAfter(e);
            ButClose.Click += (s, e) => this.Close();
            ButSend.Click += (s, e) => panelMessage1.SendMsg();
            
            ToolStrip1.ItemClicked += ToolStrip1_ItemClicked; 
            this.FormClosing += FormTalkUser_FormClosing; 
        }

        #region 属性 
        /// <summary>
        /// 当前用户名
        /// </summary>
        public string UserName
        {
            set { panelMessage1.UserName = value; }
            get { return panelMessage1.UserName; }
        }


        /// <summary>
        /// 当前用户ID
        /// </summary>
        public UInt32  UserID
        {
            set { panelMessage1.UserID = value; }
            get { return panelMessage1.UserID; }
        }
        #endregion

        #region 事件
        /// <summary>
        /// 发送事件代理
        /// </summary>
        /// <param name="Msg">要发送的消息</param>
        public delegate void CreateMsgEventHandler(object sender, Element Msg);
        /// <summary>
        /// 创建消息事件
        /// </summary>
        public event CreateMsgEventHandler CreateMsgAfter;
        /// <summary>
        /// 
        /// </summary>
        /// <param name="msg"></param>
        private void OnCreateMsgAfter(Element msg)
        {
            if (CreateMsgAfter != null)
                CreateMsgAfter(this, msg);
        }  
        #endregion

        #region 添加消息到RichTextBox
        /// <summary>
        /// 添加消息到RichTextBox
        /// </summary>
        /// <param name="msg"></param>
        /// <param name="title"></param>
        public void AddMsg(P.Message msg)
        {
            this.panelMessage1.MsgToRichTextBox(msg);
        }
        #endregion

        #region 更新自定义图片
        /// <summary>
        /// 更新自定义图片
        /// </summary>
        /// <param name="MD5"></param>
        /// <param name="image"></param>
        public void UpdateImage(string MD5, Image image)
        {
            this.panelMessage1.UpdateImage(MD5, image);
        }
        #endregion

        #region  窗体事件

        void FormTalkUser_FormClosing(object sender, FormClosingEventArgs e)
        {
            if (NewFileFLP!=null)
            {
                foreach (var c in NewFileFLP.Controls)
                {
                    FileTransmitV1 f = c as FileTransmitV1;
                    if (f != null)
                        f.CancelTransmit();
                }
                OnCreateMsgAfter(new FileMsg(OprationType.DelAll));
            }
            if (remoteHelpControl != null)
            {
                remoteHelpControl.CancelRemoteHelp();
                remoteHelpControl.Dispose();
                remoteHelpControl = null;
            }
            if (videoControl != null)
            {
                P.AVMsg Msg = new AVMsg(OprationType.Cancel);
                OnCreateMsgAfter(Msg);
                videoControl.CancelVideo();
                videoControl.Dispose();
                videoControl = null;
            } 
        }
        #endregion

        #region 工具栏事件

        void ToolStrip1_ItemClicked(object sender, ToolStripItemClickedEventArgs e)
        {
            switch (e.ClickedItem.Name)
            {
                case "tButSendFiles":
                    {
                        OpenFileDialog of = new OpenFileDialog();
                        of.Multiselect = true;
                        if (of.ShowDialog() == System.Windows.Forms.DialogResult.OK)
                            foreach (var f in of.FileNames)
                                sendFile(f);
                    }
                    break;
                case "tButRemoteHelp":
                    {
                        AddRemoteHelpTabPage(true);
                        e.ClickedItem.Enabled = false;
                    }
                    break;
                case "tButVoide":
                    {
                        AddVideoTabPage(true);
                        e.ClickedItem.Enabled = false;
                    }
                    break;
                case "tButDelFriend":
                    {
                        var To = (Tag == null ? 0 : Convert.ToUInt32(this.Tag));
                        if (Global.ShowYNCMessage(string.Format("确定要删除好友({0})吗？", To)) == DialogResult.Yes)
                            Global.MsgClient.DelFriend(To);//删除好友 
                    }
                    break;
            }
        }
        #endregion

        #region 音视频、文件传输、远程桌面

        #region 发送文件
        /// <summary>
        /// 
        /// </summary>
        IMLibrary.Controls.KRBTabControl.TabPageEx FileTabPage = null;
        /// <summary>
        /// 
        /// </summary>
        FlowLayoutPanel NewFileFLP = null;

        private void sendFile(string filename)
        {
            var md5 = Hasher.GetMD5Hash(filename);

            if (NewFileFLP != null)
                foreach (var c in NewFileFLP.Controls)
                {
                    FileTransmitV1 f = c as FileTransmitV1;
                    if (f != null && md5 == f.TFileInfo.MD5)
                        return;
                }

            if (FileTabPage == null)
            {
                FileTabPage = new IMLibrary.Controls.KRBTabControl.TabPageEx();
                FileTabPage.Font = new System.Drawing.Font("宋体", 9F);
                FileTabPage.Text = "文件";
                TabControl1.TabPages.Add(FileTabPage);
                TabControl1.SelectedTab = FileTabPage;
            }
            if (NewFileFLP == null)
            {
                NewFileFLP = new FlowLayoutPanel();
                NewFileFLP.AutoScroll = true;
                FileTabPage.Controls.Add(NewFileFLP);
                NewFileFLP.Dock = DockStyle.Fill;

                SetTabControlWidth();
            }

            FileTransmitV1 ft = new FileTransmitV1(filename, md5,
                                               Global.OfflineFileServerIP, Global.P2PServerIP, Global.OfflineFileServerPort, Global.P2PServerPort);
            NewFileFLP.Controls.Add(ft);
            ft.Width = NewFileFLP.Width - 25;

            ft.TransmitCancel += (s, e) =>
                {
                    NewFileFLP.Controls.Remove(ft);
                    if (NewFileFLP.Controls.Count == 0)
                    {
                        NewFileFLP.Dispose(); NewFileFLP = null;
                        FileTabPage.Dispose(); FileTabPage = null;
                    }
                    SetTabControlWidth();

                    var fMsg = new FileMsg(ft.TFileInfo.MD5);
                    fMsg.OprType = OprationType.Del;
                    OnCreateMsgAfter(fMsg);
                };
            ft.ServerRegistered += (s, e) =>
                {
                    var fMsg = new FileMsg(ft.TFileInfo.MD5);
                    fMsg.OprType = OprationType.Set;
                    fMsg.Length = e.ServerID;
                    OnCreateMsgAfter(fMsg);
                };
            ft.Transmitted += (s, e) =>
                {
                    panelMessage1.AddSystemMessage(" 文件“" + ft.TFileInfo.Name + "”已经传输结束！");
                    NewFileFLP.Controls.Remove(ft);
                    if (NewFileFLP.Controls.Count == 0)
                    {
                        NewFileFLP.Dispose(); NewFileFLP = null;
                        FileTabPage.Dispose(); FileTabPage = null;
                    }
                    SetTabControlWidth();
                };
            ft.OfflineFile += (s, e) =>
            {
                var fMsg = new FileMsg(ft.TFileInfo.MD5);
                fMsg.OprType = OprationType.Del;
                OnCreateMsgAfter(fMsg);
            };
            ft.OfflineFileTransmited += (s, e) =>
            {
                var fMsg = new FileMsg();
                fMsg.OprType = OprationType.Download;//标记下载离线文件
                fMsg.Name = ft.TFileInfo.Name;
                fMsg.MD5 = ft.TFileInfo.MD5;
                fMsg.Length = ft.TFileInfo.Length;
                fMsg.Extension = ft.TFileInfo.Extension;
                OnCreateMsgAfter(fMsg);
            };

            FileMsg fileMsg = new FileMsg();
            fileMsg.OprType = OprationType.New;//标记发送新文件
            fileMsg.Name = ft.TFileInfo.Name;
            fileMsg.MD5 = ft.TFileInfo.MD5;
            fileMsg.Length = ft.TFileInfo.Length;
            fileMsg.Extension = ft.TFileInfo.Extension;
            OnCreateMsgAfter(fileMsg);
        }
       
        /// <summary>
        /// 收到文件消息
        /// </summary>
        /// <param name="fileMsg"></param>
        public void ReciveFileMsg(FileMsg fileMsg)
        {
            if (fileMsg.OprType == OprationType.DelAll)
            {
                if (NewFileFLP == null)
                    return;

                foreach (var c in NewFileFLP.Controls)
                {
                    FileTransmitV1 f = c as FileTransmitV1;
                    if (f != null)
                    {
                        f.CancelTransmit();
                        f.Dispose();
                    }
                }

                NewFileFLP.Controls.Clear();
                if (FileTabPage != null)
                {
                    FileTabPage.Controls.Remove(NewFileFLP);
                    NewFileFLP.Dispose();
                    NewFileFLP = null;
                    FileTabPage.Dispose();
                    FileTabPage = null;
                }

                return;
            }

            FileTransmitV1 ft=null;
            if (NewFileFLP!= null)
                foreach (System.Windows.Forms.Control c in NewFileFLP.Controls)
                {
                    FileTransmitV1 f = c as FileTransmitV1;
                    if (f != null && fileMsg.MD5 == f.TFileInfo.MD5)
                    {
                        ft = f;
                        break;
                    }
                }

            if (ft == null && fileMsg.OprType == OprationType.New)
            {
                TFileInfo tFileinfo = new TFileInfo(fileMsg.MD5, fileMsg.Extension);
                tFileinfo.Length = fileMsg.Length;
                tFileinfo.Name = fileMsg.Name;
                ft = new FileTransmitV1(tFileinfo, Global.P2PServerIP, Global.P2PServerPort, true);

                if (FileTabPage == null)
                {
                    FileTabPage = new IMLibrary.Controls.KRBTabControl.TabPageEx();
                    FileTabPage.Font = new System.Drawing.Font("宋体", 9F);
                    FileTabPage.Text = "文件";
                    TabControl1.TabPages.Add(FileTabPage);
                    TabControl1.SelectedTab = FileTabPage;
                }
                if (NewFileFLP == null)
                {
                    NewFileFLP = new FlowLayoutPanel();
                    NewFileFLP.AutoScroll = true;
                    FileTabPage.Controls.Add(NewFileFLP);
                    NewFileFLP.Dock = DockStyle.Fill;
                    SetTabControlWidth();
                }

                NewFileFLP.Controls.Add(ft);
                ft.Width = NewFileFLP.Width - 25;

                ft.TransmitCancel += (s, e) =>
                {
                    NewFileFLP.Controls.Remove(ft);
                    if (NewFileFLP.Controls.Count == 0)
                    {
                        NewFileFLP.Dispose(); NewFileFLP = null;
                        FileTabPage.Dispose(); FileTabPage = null;
                    }
                    SetTabControlWidth();

                    var fMsg = new FileMsg(ft.TFileInfo.MD5);//文件传输协商协议
                    fMsg.OprType = OprationType.Del;//标记发送新文件 
                    OnCreateMsgAfter(fMsg);
                };
                ft.ServerRegistered += (s, e) =>
                {
                    var fMsg = new FileMsg(ft.TFileInfo.MD5);
                    fMsg.OprType = OprationType.Set;
                    fMsg.Length = e.ServerID;
                    OnCreateMsgAfter(fMsg);
                };
                ft.Transmitted += (s, e) =>
                {
                    panelMessage1.AddSystemMessage(" 文件“<file:\\\\" + ft.TFileInfo.fullName + ">”已经传输结束！");
                    NewFileFLP.Controls.Remove(ft);
                    if (NewFileFLP.Controls.Count == 0)
                    {
                        NewFileFLP.Dispose(); NewFileFLP = null;
                        FileTabPage.Dispose(); FileTabPage = null;
                    }
                    SetTabControlWidth();
                };
                return;
            }

            if (ft == null && fileMsg.OprType == OprationType.Download)
            {
                TFileInfo tFileinfo = new TFileInfo(fileMsg.MD5, fileMsg.Extension);
                tFileinfo.Length = fileMsg.Length;
                tFileinfo.Name = fileMsg.Name;
                tFileinfo.IsSend = false;
                ft = new FileTransmitV1(tFileinfo, Global.OfflineFileServerIP, Global.OfflineFileServerPort);

                if (FileTabPage == null)
                {
                    FileTabPage = new IMLibrary.Controls.KRBTabControl.TabPageEx();
                    FileTabPage.Font = new System.Drawing.Font("宋体", 9F);
                    FileTabPage.Text = "文件";
                    TabControl1.TabPages.Add(FileTabPage);
                    TabControl1.SelectedTab = FileTabPage;
                }
                if (NewFileFLP == null)
                {
                    NewFileFLP = new FlowLayoutPanel();
                    NewFileFLP.AutoScroll = true;
                    FileTabPage.Controls.Add(NewFileFLP);
                    NewFileFLP.Dock = DockStyle.Fill;
                    SetTabControlWidth();
                }
                NewFileFLP.Controls.Add(ft);
                ft.Width = NewFileFLP.Width - 25;
                
                ft.TransmitCancel += (s, e) =>
                {
                    NewFileFLP.Controls.Remove(ft);
                    if (NewFileFLP.Controls.Count == 0)
                    {
                        NewFileFLP.Dispose(); NewFileFLP = null;
                        FileTabPage.Dispose(); FileTabPage = null;
                    }
                    SetTabControlWidth(); 
                };
                ft.Transmitted += (s, e) =>
                {
                    panelMessage1.AddSystemMessage(" 文件“<file:\\\\" + ft.TFileInfo.fullName + ">”已经传输结束！"); 
                    NewFileFLP.Controls.Remove(ft);
                    if (NewFileFLP.Controls.Count == 0)
                    {
                        NewFileFLP.Dispose(); NewFileFLP = null;
                        FileTabPage.Dispose(); FileTabPage = null;
                    }
                    SetTabControlWidth();
                };
                return;
            }

            if (ft != null && fileMsg.OprType == OprationType.Del)
            {
                NewFileFLP.Controls.Remove(ft);
                ft.CancelTransmit();
                ft.Dispose();
                if (NewFileFLP.Controls.Count == 0)
                {
                    NewFileFLP.Dispose(); NewFileFLP = null;
                    FileTabPage.Dispose(); FileTabPage = null;
                }
                SetTabControlWidth();
                return;
            }
            if (ft != null && fileMsg.OprType == OprationType.Set)
            {
                ft.RequestNATIntroduction(fileMsg.Length);
                return;
            } 
        }

        #endregion

        #region 远程协助
        /// <summary>
        /// 
        /// </summary>
        IMLibrary.Controls.KRBTabControl.TabPageEx remoteTabPage = null;
        /// <summary>
        /// 
        /// </summary>
        RemoteHelpControlV1 remoteHelpControl = null;
        /// <summary>
        /// 
        /// </summary>
        /// <param name="isSelf"></param>
        private void AddRemoteHelpTabPage(bool isSelf)
        {
            if (remoteTabPage == null)
            {
                remoteTabPage = new IMLibrary.Controls.KRBTabControl.TabPageEx();
                remoteTabPage.Font = new System.Drawing.Font("宋体", 9F);
                remoteTabPage.Text = "远程";
                TabControl1.TabPages.Add(remoteTabPage);
                if (remoteHelpControl == null)
                {
                    remoteHelpControl = new RemoteHelpControlV1(Global.P2PServerIP, Global.P2PServerPort, !isSelf);
                    remoteHelpControl.ServerRegistered += (s, e) =>
                        {
                            OnCreateMsgAfter(e);
                        };
                    remoteHelpControl.Cancel += (s, e) =>
                        {
                            remoteTabPage.Controls.Remove(remoteHelpControl);
                            remoteHelpControl.Dispose();
                            remoteHelpControl = null;

                            TabControl1.TabPages.Remove(remoteTabPage);
                            remoteTabPage.Dispose();
                            remoteTabPage = null;

                            tButRemoteHelp.Enabled = true;

                            OnCreateMsgAfter(e);
                        }; 
                }
                remoteTabPage.Controls.Add(remoteHelpControl);
                remoteHelpControl.Dock = DockStyle.Fill;
                TabControl1.SelectTab(remoteTabPage);

                if (isSelf)
                {
                    P.RemoteHelp Msg = new RemoteHelp(OprationType.New);
                    OnCreateMsgAfter(Msg);
                }
            }
        }
        /// <summary>
        /// 设置远程协助参数
        /// </summary>
        /// <param name="msg"></param>
        public void SetRemoteHelp(P.RemoteHelp msg)
        {
            if (msg.OprType == OprationType.New)
            {
                tButRemoteHelp.Enabled = false ;
                AddRemoteHelpTabPage(false);
            }
            else if (msg.OprType == OprationType.Set)
            {
                if (remoteHelpControl != null)
                    remoteHelpControl.setRemoteHostIDandScreen(
                        string.Format("用户{0}({1})的桌面", UserName, UserID),
                        msg.RemoteHostID, msg.ScreenWidth, msg.ScreenHeight);
            }
            else if (msg.OprType == OprationType.Cancel)
            { 
                if (remoteTabPage != null)
                {
                    if (remoteHelpControl != null)
                    {
                        remoteTabPage.Controls.Remove(remoteTabPage);
                        remoteHelpControl.CancelRemoteHelp();
                        remoteHelpControl.Dispose();
                        remoteHelpControl = null;
                    }
                    TabControl1.TabPages.Remove(remoteTabPage);
                    remoteTabPage.Dispose();
                    remoteTabPage = null;
                }
                tButRemoteHelp.Enabled = true;
            }
        }
        #endregion

        #region 视频通信
        /// <summary>
        /// 
        /// </summary>
        IMLibrary.Controls.KRBTabControl.TabPageEx VideoTabPage = null;
        /// <summary>
        /// 
        /// </summary>
        videoControlV1 videoControl= null;
        /// <summary>
        /// 
        /// </summary>
        /// <param name="isSelf"></param>
        private void AddVideoTabPage(bool isSelf)
        {
            if (VideoTabPage == null)
            {
                VideoTabPage = new IMLibrary.Controls.KRBTabControl.TabPageEx();
                VideoTabPage.Font = new System.Drawing.Font("宋体", 9F);
                VideoTabPage.Text = "视频";
                TabControl1.TabPages.Add(VideoTabPage);
                if (videoControl == null)
                {
                    videoControl = new videoControlV1(Global.P2PServerIP, Global.P2PServerPort, !isSelf);
                    videoControl.ServerRegistered += (s, e) =>
                    {
                        OnCreateMsgAfter(e);
                    };
                    videoControl.Cancel += (s, e) =>
                    {
                        VideoTabPage.Controls.Remove(videoControl);
                        videoControl.Dispose();
                        videoControl = null;

                        TabControl1.TabPages.Remove(VideoTabPage);
                        VideoTabPage.Dispose();
                        VideoTabPage = null;

                        tButVoide.Enabled = true;
                        SetTabControlWidth();
                         
                        OnCreateMsgAfter(e);
                    };
                }
                VideoTabPage.Controls.Add(videoControl);
                videoControl.Dock = DockStyle.Fill;
                TabControl1.SelectTab(VideoTabPage);

                if (isSelf)
                {
                    P.AVMsg  Msg = new  AVMsg(OprationType.New);
                    OnCreateMsgAfter(Msg);
                }

            }
            SetTabControlWidth();
        }

        /// <summary>
        /// 设置远程协助参数
        /// </summary>
        /// <param name="msg"></param>
        public void SetAVControl(P.AVMsg msg)
        {
            if (msg.OprType == OprationType.New)
            {
                tButVoide.Enabled = false;
                AddVideoTabPage(false);
            }
            else if (msg.OprType == OprationType.Set)
            {
                if (videoControl != null)
                    videoControl.RequestNATIntroduction(msg.RemoteHostID);
            }
            else if (msg.OprType == OprationType.Cancel)
            {
                if (VideoTabPage != null)
                {
                    if (videoControl != null)
                    {
                        VideoTabPage.Controls.Remove(videoControl);
                        videoControl.CancelVideo();
                        videoControl.Dispose();
                        videoControl = null;
                    }
                    TabControl1.TabPages.Remove(VideoTabPage);
                    VideoTabPage.Dispose();
                    VideoTabPage = null;
                }
                tButVoide.Enabled = true;
                SetTabControlWidth();
            }
        }
        #endregion

        #region 更改窗口尺寸

        private bool GetFileAVControlVisible()
        {
            if (NewFileFLP != null)
                return true;
            if (videoControl != null)
                return true;
            return false;
        }

        bool isChangeSize = false;

        /// <summary>
        /// 设置右则面板和窗口宽度
        /// </summary>
        private void SetTabControlWidth()
        {
            int changeWidth =150;
            if (!isChangeSize && GetFileAVControlVisible())
            {
                this.Width += changeWidth;
                panelRight.Width += changeWidth; 
                isChangeSize = true;
            }
            else if (!GetFileAVControlVisible())
            {
                this.Width -= changeWidth;
                panelRight.Width -= changeWidth; 
                isChangeSize = false;
            }
        }
        #endregion
         
        #endregion

    }
}
